/**
 * Copyright &copy; 2016-2017 <a href="http://git.oschina.net/whoamien/backend_management">Backend Management</a> All rights reserved.
 */
package com.xw.framework.shiro;

import java.sql.Timestamp;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;

import com.xw.app.model.AcctUser;
import com.xw.app.service.AcctUserService;
import com.xw.framework.vo.UserSessionInfo;
import com.xw.util.ShiroSecurityUtil;

/**
 * The Class CustomFormAuthenticationFilter.
 *
 * @author Xi Wei
 */
public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {

	@Autowired
	private AcctUserService userService;
	
	/* (non-Javadoc)
	 * @see org.apache.shiro.web.filter.authc.FormAuthenticationFilter#onLoginSuccess(org.apache.shiro.authc.AuthenticationToken, org.apache.shiro.subject.Subject, javax.servlet.ServletRequest, javax.servlet.ServletResponse)
	 */
	@Override
	protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
			ServletResponse response) throws Exception {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		Long loginId = ShiroSecurityUtil.getLoginId();
		AcctUser user = userService.getUserAndRolesbyId(loginId);
		UserSessionInfo usi = new UserSessionInfo();
		usi.setUserName(user.getUserName());
		usi.setLoginId(loginId);
		usi.setLoginName(user.getLoginName());
		usi.setMenuList(userService.getMenuListForUser(user));
		usi.setSystemId(user.getSystemId());
		usi.setAcctUser(user);
		
		if (user.getLastLoginDate() == null) {
			usi.setFirstLogin(true);
		}
		
		httpServletRequest.getSession().setAttribute(UserSessionInfo.USER_SESSION_INFO_KEY, usi);
		httpServletRequest.getSession().setAttribute("user", user);
		user.setLastLoginDate(new Timestamp(System.currentTimeMillis()));
		userService.save(user);
		
		return super.onLoginSuccess(token, subject, request, response);
	}
}
